package com.fzu.normalservice.controller;


import com.fzu.commonutil.util.R;
import com.fzu.commonutil.entity.AddressBook;
import com.fzu.commonutil.entity.User;
import com.fzu.normalservice.service.AddressBookService;
import com.fzu.commonutil.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyq
 * @since 2023-03-26
 */
@RestController
@RequestMapping("/address-book")
public class AddressBookController {

    @Autowired
    AddressBookService addressBookService;


    /**
     * 根据用户id分页查询地址簿
     * @return
     */
    @GetMapping
    public R listAll(AddressBook addressBook,
                     @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                     @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                     @RequestHeader("token") String token) {
        User user = JwtUtil.getUser(token);
        return R.ok().data(addressBookService.ListAll(addressBook, user, pageNum, pageSize));
    }

    /**
     * 增加地址簿
     * @param addressBook
     * @param token
     * @return
     */
    @PostMapping
    public R add(@RequestBody AddressBook addressBook, @RequestHeader("token") String token){
        User user = JwtUtil.getUser(token);
        addressBook.setUserId(user.getId());
        addressBookService.save(addressBook);
        return R.ok();
    }

    /**
     * 更新地址簿
     * @param addressBook
     * @return
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook) {
        addressBookService.updateAddressBook(addressBook);
        return R.ok();
    }


    /**
     * 根据id删除地址簿
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") Integer id) {
        addressBookService.deleteAddressBook(id);
        return R.ok();
    }

    /**
     * 根据id查询地址数据
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    public R getById(@PathVariable("id") Integer id) {
        AddressBook addressBook = addressBookService.getById(id);
        return R.ok().data(addressBook);
    }
}

